<template>
  <div class="api-demo">
    <div class="demo-header">
      <h2>Python高级特性前端演示</h2>
      <p>展示如何在前端使用JavaScript高级特性对应后端Python功能</p>
    </div>

    <!-- 导航标签 -->
    <div class="demo-tabs">
      <button
        v-for="tab in tabs"
        :key="tab.id"
        :class="{ active: activeTab === tab.id }"
        @click="activeTab = tab.id"
      >
        {{ tab.name }}
      </button>
    </div>

    <!-- 装饰器演示 -->
    <div v-show="activeTab === 'decorators'" class="demo-section">
      <h3>装饰器 (Decorators)</h3>
      <div class="demo-controls">
        <button @click="testDecorators" :disabled="loading.decorators">
          {{ loading.decorators ? '测试中...' : '测试装饰器功能' }}
        </button>
        <button @click="clearDecoratorLogs" class="secondary">清除日志</button>
      </div>

      <div v-if="decoratorResult" class="demo-result">
        <h4>装饰器测试结果：</h4>
        <pre>{{ JSON.stringify(decoratorResult, null, 2) }}</pre>
      </div>

      <div class="demo-logs">
        <h4>控制台日志：</h4>
        <div class="log-container">
          <div
            v-for="(log, index) in decoratorLogs"
            :key="index"
            :class="log.type"
            class="log-item"
          >
            {{ log.message }}
          </div>
        </div>
      </div>
    </div>

    <!-- 生成器演示 -->
    <div v-show="activeTab === 'generators'" class="demo-section">
      <h3>生成器 (Generators)</h3>
      <div class="demo-controls">
        <select v-model="generatorCategory">
          <option value="">全部</option>
          <option value="热门">热门</option>
          <option value="境外">境外</option>
          <option value="景区">景区</option>
        </select>
        <button @click="testGenerator" :disabled="loading.generator">
          {{ loading.generator ? '处理中...' : '使用生成器获取数据' }}
        </button>
        <button @click="clearGeneratorLogs" class="secondary">清除日志</button>
      </div>

      <div v-if="generatorResult" class="demo-result">
        <h4>生成器处理结果：</h4>
        <p>总共处理了 {{ generatorResult.length }} 个卡片</p>
        <div class="cards-grid">
          <div
            v-for="card in generatorResult.slice(0, 6)"
            :key="card.id"
            class="demo-card"
          >
            <img :src="card.image" :alt="card.title" />
            <div class="card-info">
              <h5>{{ card.title }}</h5>
              <p>{{ card.location }} - {{ card.category }}</p>
              <p class="views">{{ card.views }} 次浏览</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 迭代器演示 -->
    <div v-show="activeTab === 'iterators'" class="demo-section">
      <h3>迭代器 (Iterators)</h3>
      <div class="demo-controls">
        <input
          v-model="iteratorFilter.views"
          type="number"
          placeholder="最小浏览量"
          min="0"
        />
        <input
          v-model="iteratorFilter.location"
          type="text"
          placeholder="地点关键词"
        />
        <button @click="testIterator" :disabled="loading.iterator">
          {{ loading.iterator ? '过滤中...' : '使用迭代器过滤' }}
        </button>
        <button @click="clearIteratorLogs" class="secondary">清除日志</button>
      </div>

      <div v-if="iteratorResult" class="demo-result">
        <h4>迭代器过滤结果：</h4>
        <p>过滤后得到 {{ iteratorResult.length }} 个卡片</p>
        <div class="filter-info">
          <p>过滤条件：浏览量 ≥ {{ iteratorFilter.views || 0 }}，包含地点 "{{ iteratorFilter.location || '全部' }}"</p>
        </div>
      </div>
    </div>

    <!-- 深浅拷贝演示 -->
    <div v-show="activeTab === 'copy'" class="demo-section">
      <h3>深浅拷贝 (Deep & Shallow Copy)</h3>
      <div class="demo-controls">
        <button @click="testCopyDemo" :disabled="loading.copy">
          {{ loading.copy ? '演示中...' : '演示深浅拷贝' }}
        </button>
        <button @click="clearCopyLogs" class="secondary">清除日志</button>
      </div>

      <div v-if="copyResult" class="demo-result">
        <h4>深浅拷贝对比：</h4>
        <div class="copy-comparison">
          <div class="copy-item">
            <h5>原始数据</h5>
            <pre>{{ JSON.stringify(copyResult.original, null, 2) }}</pre>
          </div>
          <div class="copy-item">
            <h5>浅拷贝</h5>
            <pre>{{ JSON.stringify(copyResult.shallow, null, 2) }}</pre>
          </div>
          <div class="copy-item">
            <h5>深拷贝</h5>
            <pre>{{ JSON.stringify(copyResult.deep, null, 2) }}</pre>
          </div>
        </div>
        <div class="copy-message">
          <p>{{ copyResult.message }}</p>
        </div>
      </div>
    </div>

    <!-- 静态方法演示 -->
    <div v-show="activeTab === 'static'" class="demo-section">
      <h3>静态方法 (Static Methods)</h3>
      <div class="demo-controls">
        <button @click="testStaticMethods" :disabled="loading.static">
          {{ loading.static ? '测试中...' : '测试静态方法' }}
        </button>
        <button @click="clearStaticLogs" class="secondary">清除日志</button>
      </div>

      <div v-if="staticResult" class="demo-result">
        <h4>静态方法测试结果：</h4>
        <div class="static-info">
          <p>总卡片数：{{ staticResult.total_cards }}</p>
          <p>热门卡片数：{{ staticResult.hot_cards_count }}</p>
        </div>
        <div class="cards-grid">
          <div
            v-for="card in staticResult.sample_cards"
            :key="card.id"
            class="demo-card"
          >
            <img :src="card.image" :alt="card.title" />
            <div class="card-info">
              <h5>{{ card.title }}</h5>
              <p>{{ card.location }} - {{ card.category }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 认证演示 -->
    <div v-show="activeTab === 'auth'" class="demo-section">
      <h3>认证系统 (Authentication)</h3>

      <div v-if="!isLoggedIn" class="auth-forms">
        <div class="form-section">
          <h4>登录</h4>
          <div class="form-group">
            <input v-model="loginForm.username" placeholder="用户名" />
            <input v-model="loginForm.password" type="password" placeholder="密码" />
            <button @click="handleLogin" :disabled="loading.login">
              {{ loading.login ? '登录中...' : '登录' }}
            </button>
          </div>
        </div>

        <div class="form-section">
          <h4>注册</h4>
          <div class="form-group">
            <input v-model="registerForm.username" placeholder="用户名" />
            <input v-model="registerForm.email" placeholder="邮箱" />
            <input v-model="registerForm.password" type="password" placeholder="密码" />
            <input v-model="registerForm.nickname" placeholder="昵称（可选）" />
            <button @click="handleRegister" :disabled="loading.register">
              {{ loading.register ? '注册中...' : '注册' }}
            </button>
          </div>
        </div>
      </div>

      <div v-else class="user-info">
        <h4>当前用户：{{ userInfo.username }}</h4>
        <p>邮箱：{{ userInfo.email }}</p>
        <p>昵称：{{ userInfo.nickname || '未设置' }}</p>
        <button @click="handleLogout" class="secondary">退出登录</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import apiService from '@/services/apiService'

// 响应式数据
const activeTab = ref('decorators')
const loading = reactive({
  decorators: false,
  generator: false,
  iterator: false,
  copy: false,
  static: false,
  login: false,
  register: false
})

const decoratorResult = ref(null)
const generatorResult = ref(null)
const iteratorResult = ref(null)
const copyResult = ref(null)
const staticResult = ref(null)

const generatorCategory = ref('')
const iteratorFilter = reactive({
  views: '',
  location: ''
})

const decoratorLogs = ref([])
const generatorLogs = ref([])
const iteratorLogs = ref([])
const copyLogs = ref([])
const staticLogs = ref([])

const isLoggedIn = ref(false)
const userInfo = ref({})

const loginForm = reactive({
  username: '',
  password: ''
})

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  nickname: ''
})

// 标签配置
const tabs = [
  { id: 'decorators', name: '装饰器' },
  { id: 'generators', name: '生成器' },
  { id: 'iterators', name: '迭代器' },
  { id: 'copy', name: '深浅拷贝' },
  { id: 'static', name: '静态方法' },
  { id: 'auth', name: '认证系统' }
]

// 拦截console.log来收集日志
const originalConsoleLog = console.log
const originalConsoleError = console.error
const originalConsoleWarn = console.warn

function setupConsoleInterceptor(logsRef, prefix = '') {
  return {
    log: (...args) => {
      logsRef.value.push({ type: 'log', message: `${prefix}${args.join(' ')}` })
      originalConsoleLog(...args)
    },
    error: (...args) => {
      logsRef.value.push({ type: 'error', message: `${prefix}${args.join(' ')}` })
      originalConsoleError(...args)
    },
    warn: (...args) => {
      logsRef.value.push({ type: 'warn', message: `${prefix}${args.join(' ')}` })
      originalConsoleWarn(...args)
    }
  }
}

// 测试装饰器功能
const testDecorators = async () => {
  loading.decorators = true
  decoratorResult.value = null
  decoratorLogs.value = []

  // 临时拦截console
  const interceptor = setupConsoleInterceptor(decoratorLogs, '[装饰器] ')
  const oldLog = console.log
  const oldError = console.error
  const oldWarn = console.warn

  console.log = interceptor.log
  console.error = interceptor.error
  console.warn = interceptor.warn

  try {
    // 测试缓存装饰器
    console.log('开始测试缓存装饰器...')
    const result1 = await apiService.getCards('热门', 1, 5)
    const result2 = await apiService.getCards('热门', 1, 5)
    console.log('缓存测试完成')

    // 测试重试装饰器
    console.log('开始测试重试装饰器...')
    // 这里会触发重试机制
    const retryResult = await apiService.getCards('不存在分类', 1, 5)
    console.log('重试测试完成')

    decoratorResult.value = {
      cache_test: '连续调用相同API，应该看到缓存提示',
      retry_test: '尝试访问不存在的分类，应该看到重试提示',
      result1_total: result1.total,
      result2_total: result2.total
    }
  } catch (error) {
    console.error('装饰器测试失败:', error.message)
    decoratorResult.value = { error: error.message }
  } finally {
    // 恢复原始console
    console.log = oldLog
    console.error = oldError
    console.warn = oldWarn
    loading.decorators = false
  }
}

// 测试生成器功能
const testGenerator = async () => {
  loading.generator = true
  generatorResult.value = null

  try {
    const result = await apiService.getCardsWithGenerator(generatorCategory.value)
    generatorResult.value = result
  } catch (error) {
    console.error('生成器测试失败:', error)
    generatorResult.value = []
  } finally {
    loading.generator = false
  }
}

// 测试迭代器功能
const testIterator = async () => {
  loading.iterator = true
  iteratorResult.value = null

  try {
    const filterFn = (card) => {
      const meetsViews = !iteratorFilter.views || card.views >= parseInt(iteratorFilter.views)
      const meetsLocation = !iteratorFilter.location ||
        card.location.includes(iteratorFilter.location) ||
        card.title.includes(iteratorFilter.location)

      return meetsViews && meetsLocation
    }

    const result = await apiService.getFilteredCards(filterFn, generatorCategory.value)
    iteratorResult.value = result
  } catch (error) {
    console.error('迭代器测试失败:', error)
    iteratorResult.value = []
  } finally {
    loading.iterator = false
  }
}

// 测试深浅拷贝
const testCopyDemo = async () => {
  loading.copy = true
  copyResult.value = null

  try {
    const result = await apiService.demonstrateCopy()
    copyResult.value = result
  } catch (error) {
    console.error('拷贝演示失败:', error)
  } finally {
    loading.copy = false
  }
}

// 测试静态方法
const testStaticMethods = async () => {
  loading.static = true
  staticResult.value = null

  try {
    const result = await apiService.getCards() // 这会调用静态方法
    staticResult.value = result
  } catch (error) {
    console.error('静态方法测试失败:', error)
  } finally {
    loading.static = false
  }
}

// 认证相关方法
const handleLogin = async () => {
  if (!loginForm.username || !loginForm.password) {
    alert('请输入用户名和密码')
    return
  }

  loading.login = true
  try {
    const result = await apiService.login(loginForm.username, loginForm.password)
    isLoggedIn.value = true
    userInfo.value = result.user
    alert('登录成功！')
  } catch (error) {
    alert(`登录失败：${error.message}`)
  } finally {
    loading.login = false
  }
}

const handleRegister = async () => {
  if (!registerForm.username || !registerForm.email || !registerForm.password) {
    alert('请填写所有必填字段')
    return
  }

  loading.register = true
  try {
    const result = await apiService.register({
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      nickname: registerForm.nickname
    })
    alert('注册成功！请登录')
  } catch (error) {
    alert(`注册失败：${error.message}`)
  } finally {
    loading.register = false
  }
}

const handleLogout = () => {
  localStorage.removeItem('access_token')
  isLoggedIn.value = false
  userInfo.value = {}
  alert('已退出登录')
}

// 清除日志方法
const clearDecoratorLogs = () => { decoratorLogs.value = [] }
const clearGeneratorLogs = () => { generatorLogs.value = [] }
const clearIteratorLogs = () => { iteratorLogs.value = [] }
const clearCopyLogs = () => { copyLogs.value = [] }
const clearStaticLogs = () => { staticLogs.value = [] }

// 检查登录状态
onMounted(() => {
  const token = localStorage.getItem('access_token')
  if (token) {
    apiService.setToken(token)
    isLoggedIn.value = true
    // 获取用户信息
    // 这里可以添加获取用户信息的逻辑
  }
})
</script>

<style scoped>
.api-demo {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.demo-header {
  text-align: center;
  margin-bottom: 30px;
}

.demo-header h2 {
  color: #1976d2;
  margin-bottom: 10px;
}

.demo-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
  border-bottom: 1px solid #e0e0e0;
}

.demo-tabs button {
  padding: 10px 20px;
  border: none;
  background: none;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.demo-tabs button.active {
  color: #1976d2;
  border-bottom-color: #1976d2;
  font-weight: 600;
}

.demo-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.demo-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.demo-controls input,
.demo-controls select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.demo-controls button {
  padding: 8px 16px;
  background: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.demo-controls button:hover:not(:disabled) {
  background: #1565c0;
}

.demo-controls button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.demo-controls button.secondary {
  background: #666;
}

.demo-result {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
}

.demo-logs {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
}

.log-item {
  padding: 4px 8px;
  margin-bottom: 2px;
  border-radius: 3px;
  font-family: monospace;
  font-size: 12px;
}

.log-item.log {
  background: #e3f2fd;
  color: #1976d2;
}

.log-item.error {
  background: #ffebee;
  color: #d32f2f;
}

.log-item.warn {
  background: #fff3e0;
  color: #f57c00;
}

.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 20px;
}

.demo-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.3s;
}

.demo-card:hover {
  transform: translateY(-2px);
}

.demo-card img {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.card-info {
  padding: 10px;
}

.card-info h5 {
  margin: 0 0 5px 0;
  font-size: 14px;
}

.card-info p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.views {
  color: #ff6b35;
  font-weight: 600;
}

.copy-comparison {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.copy-item {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.copy-item h5 {
  margin-top: 0;
  color: #1976d2;
}

.copy-message {
  margin-top: 20px;
  padding: 15px;
  background: #e8f5e8;
  border-radius: 8px;
  color: #2e7d32;
}

.auth-forms {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
}

.form-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.form-group input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.user-info {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.user-info h4 {
  color: #1976d2;
  margin-bottom: 10px;
}

@media (max-width: 768px) {
  .demo-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .auth-forms {
    grid-template-columns: 1fr;
  }

  .copy-comparison {
    grid-template-columns: 1fr;
  }

  .cards-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>
